//给定一个二叉树，返回其节点值的锯齿形层序遍历。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。 
//
// 例如： 
//给定二叉树 [3,9,20,null,null,15,7], 
//
// 
//    3
//   / \
//  9  20
//    /  \
//   15   7
// 
//
// 返回锯齿形层序遍历如下： 
//
// 
//[
//  [3],
//  [20,9],
//  [15,7]
//]
// 
// Related Topics 树 广度优先搜索 二叉树 
// 👍 459 👎 0

/**
 * @author DaHuangXiao
 */
package leetcode.editor.cn;

import sun.awt.image.ImageWatched;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BinaryTreeZigzagLevelOrderTraversal {
    public static void main(String[] args) {
        Solution solution = new BinaryTreeZigzagLevelOrderTraversal().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        Queue<TreeNode> stack = new LinkedList<>();
        LinkedList<List<Integer>> res = new LinkedList<>();
        if (root==null){
            return res;
        }
        stack.offer(root);
        int flag = -1;
        while (!stack.isEmpty()){
            int size = stack.size();
            LinkedList<Integer> tempList  =new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = stack.poll();
                if (flag==-1) {
                    tempList.add(cur.val);
                }else {
                    tempList.addFirst(cur.val);
                }
                if (cur.left!=null){
                    stack.offer(cur.left);
                }
                if (cur.right!=null){
                    stack.offer(cur.right);
                }
            }
            flag*=-1;
            res.add(tempList);
        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}